
 
from pywinauto.application import Application
from pywinauto.uia_element_info import UIAElementInfo
from pywinauto.uia_defines import IUIA
from pywinauto.controls.uia_controls import StaticWrapper
from pywinauto.controls.uia_controls import EditWrapper
from pywinauto.controls.uia_controls import ListViewWrapper
from pywinauto.controls.uiawrapper import UIAWrapper
from pywinauto.keyboard import send_keys
import time

from PIL import ImageGrab, Image

 

class pywinautohelper:

    def __init__(self, titleName="Network Analyzer"):

       self.app = Application(backend="uia").connect(title=titleName)


       #self.app =
       #Application(backend="uia").connect(path=r"D:\VNAFull\VNAFull\Source\UI\VNAApplication\bin\x64\Debug\Network
       #Analyzer.exe")
       self.dlg = self.app.top_window()
       self.rightControl = self.dlg.child_window(auto_id = 'rightControl')
       self.rightPanel = self.rightControl.child_window(auto_id="scrollViewer", control_type="Pane")
       #self.dlg.print_control_identifiers()


    #return uiawrapper.UIAWrapper
    def GetRightPanel(self):
        rightPanelObj = self.rightPanel.wrapper_object()
        assert isinstance(rightPanelObj,UIAWrapper)
        return rightPanelObj

    #return uiawrapper.UIAWrapper
    def GetRightCheckButton(self,btnName):
        obj = self.dlg[btnName].wrapper_object()
        obj2 = obj.parent().children(auto_id='downLabel').pop(0)
        assert isinstance(obj2,UIAWrapper)
        return obj2

    #return uiawrapper.UIAWrapper
    def GetRightNormalButton(self,btnName):
        obj = self.rightPanel.child_window(title=btnName,control_type="Custom").wrapper_object().parent()
        assert isinstance(obj,UIAWrapper)
        return obj

    #return uiawrapper.UIAWrapper
    def GetDg(self,dgAutoId='AutoIdMDgdSwpSetSeg'):
        dg = self.dlg.child_window(auto_id = dgAutoId).wrapper_object()
        assert isinstance(dg,ListViewWrapper)
        return dg

    #return uiawrapper.UIAWrapper
    def GetDgCell(self,row,col,dgAutoId='AutoIdMDgdSwpSetSeg'):
        dg = self.dlg.child_window(auto_id = dgAutoId)
        cell = dg.wrapper_object().cell(row,col)
        assert isinstance(cell,UIAWrapper)
        return cell

    #return uiawrapper.StaticWrapper
    def GetCellContent(self,cell):
        child = cell.children().pop(0)

        if child.element_info.control_type == 'Custom':
            child = child.children().pop(0)
       
        return child

    #return 0:普通 1：选中 2：编辑
    def GetDgCellStatus(self,row,cell,dgAutoId='AutoIdMDgdSwpSetSeg'):
        dg = self.dlg.child_window(auto_id = dgAutoId)
        cell = dg.wrapper_object().cell(row,cell)
        status = 0

        if cell.is_selected() == 1:
            status = 1
    
        child = cell.children().pop(0)
        if child.element_info.control_type == 'Custom':
            status = 2

        #if child.element_info.control_type == 'Edit':
        #    status = 2

        return status



class UseCaseHelper:

    def __init__(self):
       self.helper = pywinautohelper()

    #1,点击button(不同类别的button实现是否有差异？)
    def UserCase1(self):
       btn = self.helper.GetRightCheckButton("Measurement")
       btn.click_input()

       btn1 = self.helper.GetRightNormalButton("S31")
       btn1.click_input()

       assert self.helper.GetRightCheckButton("Measurement").texts()[0] == "S31"

       

       panel = self.helper.GetRightPanel()
       if panel.iface_scroll.CurrentVerticallyScrollable:
            panel.scroll("down","page",10)
       btn2 = self.helper.GetRightNormalButton("Return")
       btn2.click_input()

    #2，获取button的显示内容(如Freq Mode按钮的Start/stop，获取Points按钮的数值等)
    def UserCase2(self):
       btn = self.helper.GetRightNormalButton("Sweep Setup")
       btn.click_input()

       btn1 = self.helper.GetRightNormalButton("Edit Segment Table")
       btn1.click_input()


       print("Freq Mode:" + self.helper.GetRightCheckButton("Freq Mode").window_text())

       print("Cell Points:" + self.helper.GetCellContent(self.helper.GetDgCell(0,4)).window_text())

       self.helper.GetRightPanel().scroll("down","page",10)
       btn2 = self.helper.GetRightNormalButton("Return")
       btn2.click_input()

       btn3 = self.helper.GetRightNormalButton("Return")
       btn3.click_input()

    #3，对button截图保存
    #4，获取按钮是否处于禁用状态（例如分段表的点数满了以后，add按钮就置灰）
    #5，获取分段表的各个cell的值，获取cell的选中状态
    def UserCase3(self):

      obj = self.helper.rightControl.child_window(auto_id="label", found_index=0).wrapper_object()
      assert isinstance(obj,UIAWrapper)
      
      print(obj.window_text())
       #btn = self.helper.GetRightNormalButton("Sweep Setup")
       #btn.click_input()

       #btn1 = self.helper.GetRightNormalButton("Edit Segment Table")
       #btn1.click_input()

       #cell = self.helper.GetDgCell(0,2)
       #cell.click_input()
       #print("cell Points status(0:普通 1：选中 2：编辑):" +
       #str(self.helper.GetDgCellStatus(0,4)))

       #cell.click_input()
       #status = self.helper.GetDgCellStatus(0,2)
       #print("cell Points status(0:普通 1：选中 2：编辑):" + str(status))

       #if status == 2:
       #  edit = self.helper.GetCellContent(cell)
       #  assert isinstance(edit,EditWrapper)
       #  edit.set_text(400)
         #edit.click_input(coords=(edit.rectangle().width() - 10,None))
         #edit.type_keys("{VK_RBUTTON}")
         #edit.type_keys("{k down}""{k up}")
         #edit.type_keys("{VK_SHIFT down}""m""{VK_SHIFT up}")
        
       #time.sleep(0.1)
       #btnadd = self.helper.GetRightNormalButton("Add")
       #count = 0
       #while count < 5:
       #     btnadd.click_input()
       #     count = count + 1
       #img1 = btnadd.capture_as_image()
       #img1.save('screenshot5.png')

       #self.helper.GetRightPanel().scroll("down","page",10)
       #btn2 = self.helper.GetRightNormalButton("Return")
       #btn2.click_input()

       #btn3 = self.helper.GetRightNormalButton("Return")
       #btn3.click_input()

    #6、delete/add/clear后，获取分段表对应操作的变化
    #7、关闭参数显示，获取分段表对应参数的隐藏状态
    def UserCase4(self):
       btn = self.helper.GetRightNormalButton("Sweep Setup")
       btn.click_input()

       btn1 = self.helper.GetRightNormalButton("Edit Segment Table")
       btn1.click_input()

       dg = self.helper.GetDg()

       btnClear = self.helper.GetRightNormalButton("Clear Seg Table")
       btnClear.click_input()
       btnOK = self.helper.GetRightNormalButton("OK")
       btnOK.click_input()
 
       rowcount = dg.item_count()
       assert rowcount == 2

       btnAdd = self.helper.GetRightNormalButton("Add")
       btnAdd.click_input()
       rowcount = dg.item_count()
       assert rowcount == 3

       btnDel = self.helper.GetRightNormalButton("Delete")
       btnDel.click_input()
       rowcount = dg.item_count()
       assert rowcount == 2

       
       btnListIFBW = self.helper.GetRightCheckButton("List IFBW")

       btnListIFBW.click_input()
       print(btnListIFBW.window_text())
       IFBW = dg.get_column(5)
       print(IFBW.is_visible())


       btnListIFBW.click_input()
       print(btnListIFBW.window_text())
       IFBW = dg.get_column(5)
       print(IFBW.is_visible())



       self.helper.GetRightPanel().scroll("down","page",10)
       btn2 = self.helper.GetRightNormalButton("Return")
       btn2.click_input()

       btn3 = self.helper.GetRightNormalButton("Return")
       btn3.click_input()


helper1 = UseCaseHelper()
helper1.UserCase3()



#helper = pywinautohelper()
#print(helper.GetRightCheckButton("List IFBW").texts()[0])
#print(helper.GetDgCell(0,4).texts()[0])
#print(helper.GetDgCellStatus(1,4))
#btn = helper.GetRightNormalButton("Add")
#btn.click_input(button='left')
#cell = helper.GetDgCell(10,0)
#try:
#    cell.double_click_input(button='left')
#except Exception as err:
#    print(err)

#print(helper.GetCellContent(cell).window_text())
#btn = helper.GetRightNormalButton("Add")
#print(btn.automation_id())
#while(True):
#    try:
#        btnType = input("Is Normal? ")
#        btnName = input("button Name? ")
#        if btnType == "1":
#            btn = helper.GetRightNormalButton(btnName)
#            btn.click_input();
#            print(btn.automation_id())
#        else:
#            btn = helper.GetRightCheckButton(btnName)
#            btn.click_input();
#            print(btn.texts()[0])
#    except Exception as err:
#        print(err)

#print(btn.is_enabled())

#img1 = btn.capture_as_image()
#assert isinstance(img1,Image)
#img1.save('screenshot4.png')
#img1._show()